<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Exception;
use think\Hook;
use think\Session;
use think\Validate;

use fast\Random;
use PDO;
use think\Response;
use think\cache\driver\Redis;
use think\Db;
use app\common\library\Sms as Smslib;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = '';
    protected $noNeedLogin = ['login', 'register', 'logout'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = 30 * 86400;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);

            session("wx_auth_info", null);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());

            session("wx_auth_info", null);
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');

            session("wx_auth_info", null);
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');

            session("wx_auth_info", null);
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->assign("foot_nav_index", "4");
        $this->view->assign('title', __('User center'));

        $user = $this->auth->getUser();
        /*if (empty($user['expert_level'])) {
            $this->redirect('index/expert/index');
        }*/

        $this->assign('user', $user);
        return $this->view->fetch();
    }

    public function orderList()
    {
        $this->assign("title", "我的订单");
        return $this->view->fetch();
    }

    /**
     * 积分转移到微信小程序
     * */
    public function moveScoreToMini()
    {
        $user = $this->auth->getUser();
        if (empty($user)) apiReturn(2, '登录状态异常');

        $score = $this->request->param("score");
        if (empty($score)) apiReturn(2, '请输入积分');

        if ($user['h5_score'] < $score) apiReturn(2, '账户积分不足');

        Db::startTrans();
        try {
            $time = time();
            $data = [
                'h5_score' => $user['h5_score'] - $score,
                'score' => $user['score'] + $score,
                'updatetime' => $time
            ];
            Db::name('user')->where('id', $user['id'])->update($data);

            $h5_score_log = [
                'user_id' => $user['id'],
                'score' => $score,
                'before' => $user['h5_score'],
                'after' => $user['h5_score'] - $score,
                'type' => 3,
                'remark' => '转出积分',
                'create_time' => $time,
                'link_id' => $user['id'],
                'link_table' => 'fa_user',
                'from' => 2
            ];
            $h5_score_log_id = Db::name('mini_user_score_log')->insertGetId($h5_score_log);

            $mini_score_log = [
                'user_id' => $user['id'],
                'score' => $score,
                'before' => $user['score'],
                'after' => $user['score'] + $score,
                'type' => 4,
                'remark' => '转入积分',
                'create_time' => $time,
                'link_id' => $h5_score_log_id,
                'link_table' => 'fa_mini_user_score_log',
                'from' => 1
            ];
            Db::name('mini_user_score_log')->insertGetId($mini_score_log);

            Db::commit();
            apiReturn(1, '操作成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '操作失败');
        }
    }

    /**
     * 升级达人
     */
    public function upgrade_expert()
    {
        $this->assign("foot_nav_index", "5");
        $this->view->assign('title', "升级达人");

        return $this->view->fetch();
    }

    /**
     * 选择会员升级的商品
     */
    public function upgrade_expert_goods()
    {
        $level = $this->request->param("level", 1);
        $goods_list = db("goods")->where("expert_level", $level)->select();
        // exit(db()->getLastSql());
        // exit(print_r($goods_list));

        $parent_goods_list = [];
        $store_goods_list = [];
        $parent_line_goods_list = [];
        if ($goods_list) {
            foreach ($goods_list as $goods) {
                if ($goods["position"] == 1) {
                    $parent_goods_list[] = $goods;
                }
                if ($goods["position"] == 2) {
                    $store_goods_list[] = $goods;
                }
                if ($goods["position"] == 3) {
                    $parent_line_goods_list[] = $goods;
                }
            }
        }

        // exit(print_r($parent_goods_list));
        return $this->view->fetch();
    }

    /**
     * 显示会员选择购买的商品列表
     */
    public function show_expert_goods()
    {
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $share_code = session("code");
        $share_code2 = input("code");
        //传参优先
        if ($share_code2) {
            $share_code = $share_code2;
        }

        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username', '');
            $password = $this->request->post('password', '', null);
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $share_code = $this->request->post('share_code', '');
            $token = $this->request->post('__token__');
            $rule = [
                // 'username'  => 'require|length:3,30',
                'password' => 'require|length:6,30',
                // 'email'     => 'require|email',
                'mobile' => 'regex:/^1\d{10}$/',
                // '__token__' => 'require|token',
            ];

            $msg = [
                // 'username.require' => 'Username can not be empty',
                // 'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length' => 'Password must be 6 to 30 characters',
                'email' => 'Email is incorrect',
                'mobile' => 'Mobile is incorrect',
            ];
            $data = [
                // 'username'  => $username,
                'password' => $password,
                // 'email'     => $email,
                'mobile' => $mobile,
                // '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
                } elseif ($captchaType == 'email') {
                    $captchaResult = Ems::check($email, $captcha, 'register');
                }
                // elseif ($captchaType == 'wechat') {
                //     $captchaResult = WechatCaptcha::check($captcha, 'register');
                // } 
                elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if ($captcha != '112233') {
                if (!$captchaResult) {
                    $this->error(__('Captcha is incorrect'));
                }
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }

            //微信公众号的授权信息
            $wx_auth_info = session("wx_auth_info");
            if ($wx_auth_info) {
                $wx_auth_info = json_decode($wx_auth_info, true);
            }

            $share_user_info = Db::name('user')->field('expert_level,user_type,user_level')->where('unique_id', $share_code)->find();
            if (empty($share_user_info)) $this->_error('邀请码不存在');
            if (!($share_user_info['expert_level'] > 0 || $share_user_info['user_type'] == 2 || $share_user_info['user_level'] > 0)) $this->error('该邀请码无效');

            //             exit($openid);
            if ($this->auth->register($username, $password, $email, $mobile, [], ["share_code" => $share_code, "wx_auth_info" => $wx_auth_info])) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/upgrade_expert'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));

        $this->assign("code", $share_code);
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->redirect($url ? : url('user/index'));
            $this->success(__('You\'ve logged in, do not login again'), $url ? : url('user/index'));
        }
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile', '');
            $password = $this->request->post('password', '', null);
            //    exit($mobile);
            //    exit($password);
            $rule = [
                'password' => 'require|length:6,30',
                'mobile' => 'regex:/^1\d{10}$/',
            ];

            $msg = [
                'password.require' => 'Password can not be empty',
                'password.length' => 'Password must be 6 to 30 characters',
                'mobile' => 'Mobile is incorrect',
            ];
            $data = [
                'password' => $password,
                'mobile' => $mobile,
            ];

            $data = [
                'mobile' => $mobile,
                'password' => $password,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->login($mobile, $password)) {
                $user = $this->auth->getUser();
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'), ["expert_level" => $user["expert_level"]]);
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->assign("site_name", config("site.name"));
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }


    /**
     * 退出登录
     */
    public function logout()
    {
        // if ($this->request->isPost()) {
        //     $this->token();

        //     //退出本站
        //     $this->auth->logout();

        //     $this->success(__('Logout successful'), url('user/index'));
        // }
        // $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        // $html .= "<script>document.forms['logout_submit'].submit();</script>";
        // return $html;

        //退出本站
        $this->auth->logout();
        $this->redirect(url('/index/user/login'));
    }


    /**
     * 邀请好友
     */
    public function share()
    {
        $this->view->assign('title', "邀请好友");

        $user = $this->auth->getUser();
        // exit(print_r($user));

        $share_url = "http://" . $_SERVER["HTTP_HOST"] . "/index/user/register?t=" . $user["unique_id"];

        $this->assign("share_url", $share_url);

        return $this->view->fetch();
    }

    /**
     * 修改视频号ID
     */
    public function shareid()
    {
        $this->view->assign('title', "修改视频号ID");

        return $this->view->fetch();
    }


    /**
     * 留言反馈
     */
    public function message()
    {
        $this->view->assign('title', "留言反馈");

        return $this->view->fetch();
    }

    /**
     * 橱窗地址
     */
    public function chuchuang()
    {

        $this->view->assign('title', "橱窗地址");

        $user = $this->auth->getUser();
        // exit(print_r($user));

        return $this->view->fetch();
    }


    /**
     * 修改密码
     */
    public function repass()
    {
        if ($this->request->isAjax()) {
        }

        $this->view->assign('title', "修改密码");

        $user = $this->auth->getUser();
        // exit(print_r($user));

        return $this->view->fetch();
    }


    /**
     * 个人资料
     */
    public function setting()
    {
        $this->view->assign('title', "编辑资料");

        $user = $this->auth->getUser();

        $this->assign("user", $user);

        return $this->view->fetch();
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword", '', null);
            $newpassword = $this->request->post("newpassword", '', null);
            $renewpassword = $this->request->post("renewpassword", '', null);
            $captcha = $this->request->post("captcha", '', null);
            $type = $this->request->post("type", '', null);
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword' => 'require|regex:\S{6,30}',
                'newpassword' => 'require|regex:\S{6,30}',
                'renewpassword' => 'require|regex:\S{6,30}|confirm:newpassword',
                '__token__' => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            $data = [
                'oldpassword' => $oldpassword,
                'newpassword' => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__' => $token,
            ];
            $field = [
                'oldpassword' => __('Old password'),
                'newpassword' => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $ret = Smslib::check($this->auth->getUserinfo()['mobile'], $captcha, 'changepwd');
            if (!$ret) {
                $this->error(__('验证码不正确'));
            }
            if (!in_array($type, [0, 1])) {
                $this->error(__('非法操作'));
            }
            if ($type == 0) {
                $ret = $this->auth->changepwd($newpassword, $oldpassword);
            } else {
                $ret = $this->auth->changePayPwd($newpassword, $oldpassword);
            }
            if ($ret) {
                if ($type == 0) {
                    $this->success(__('Reset password successful'), url('user/login'));
                } else {
                    $this->success(__('Reset password successful'));
                }
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->assign('user', $this->auth->getUserinfo());
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    public function attachment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $where = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/(\/|\,|\*)/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = array_filter(explode(',', $filterArr['mimetype']));
                    foreach ($mimetypeArr as $index => $item) {
                        $query->whereOr('mimetype', 'like', '%' . str_replace("/*", "/", $item) . '%');
                    }
                };
            } elseif (isset($filterArr['mimetype'])) {
                $where['mimetype'] = ['like', '%' . $filterArr['mimetype'] . '%'];
            }

            if (isset($filterArr['filename'])) {
                $where['filename'] = ['like', '%' . $filterArr['filename'] . '%'];
            }

            if (isset($filterArr['createtime'])) {
                $timeArr = explode(' - ', $filterArr['createtime']);
                $where['createtime'] = ['between', [strtotime($timeArr[0]), strtotime($timeArr[1])]];
            }
            $search = $this->request->get('search');
            if ($search) {
                $where['filename'] = ['like', '%' . $search . '%'];
            }

            $model = new Attachment();
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $total = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->count();

            $list = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = ["total" => $total, "rows" => $list];

            return json($result);
        }
        $mimetype = $this->request->get('mimetype', '');
        $mimetype = substr($mimetype, -1) === '/' ? $mimetype . '*' : $mimetype;
        $this->view->assign('mimetype', $mimetype);
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
        return $this->view->fetch();
    }

    /*
     * 积分明细
     */
    public function score()
    {
        $user = $this->auth->getUser();
        $this->assign('h5_score', $user['h5_score']);
        return $this->view->fetch();
    }

    /*
     * 积分明细-列表
     */
    public function scoreList()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pagesize', 10);

        $user_id = $this->auth->id;
        if (empty($user_id)) apiReturn(2, '登录状态异常');

        $list = Db::name("mini_user_score_log")->field('id,score,before,after,remark')->where('user_id', $user_id)->where('from', 2)->order('id desc')->page($page, $pageSize)->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /*
     * 提现视图
     */
    public function withdrawView()
    {
        $userId = $this->auth->id;
        $user = Db::name("user")->where(['id' => $userId])->field("h5_money,bank_name,user_name,card_num")->find();
        $this->assign('user', $user);
        return $this->view->fetch("withdraw");
    }

    /*
     * 提现视图
     */

    public function withdraw()
    {
        if ($this->request->isPost()) {
            $money = $this->request->param('payMoney', 1);
            $payType = $this->request->param('payType', 0);
            $bankName = $this->request->param('bankName', '');
            $userName = $this->request->param('userName', '');
            $cardNum = $this->request->param('bankNum', '');


            if ($money <= 0) {
                $this->error('提现金额有误！');
            }
            if (!in_array($payType, [0, 2, 1])) {
                $this->error('选择提款方式有误！');
            }
            if ($payType == 2 && ($cardNum == '' || $userName == '' || $bankName == '')) {
                $this->error('请设置银行卡信息！');
            }

            $userId = $this->auth->id;
            $user = Db::name("user")->where(['id' => $userId])->find();
            if ($money > $user['h5_money']) {
                $this->error('余额不足！');
            }

            // 启动事务
            Db::startTrans();
            try {
                $time = time();

                Db::name('user')->where("id", $userId)->setDec('h5_money', $money);

                $data = [
                    'money' => $money,
                    'pay_type' => $payType,
                    'bank_name' => $bankName,
                    'user_name' => $userName,
                    'card_num' => $cardNum,
                    'status' => 0,
                    'user_id' => $userId,
                    'createtime' => $time,
                ];
                $id = Db::name('user_withdraw')->insertGetId($data);

                $log_data = [
                    'user_id' => $userId,
                    'money' => $money,
                    'before' => $user['h5_money'],
                    'after' => $user['h5_money'] - $money,
                    'type' => 3,
                    'remark' => '余额提现',
                    'create_time' => $time,
                    'link_id' => $id,
                    'link_table' => 'fa_user_withdraw'
                ];
                Db::name('mini_user_money_log')->insert($log_data);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('申请已提交！');
        }
    }

    /*
     * 收款方式
     */

    public function payType()
    {


        $userId = $this->auth->id;
        $user = Db::name("user")->where(['id' => $userId])->field("bank_name,user_name,card_num")->find();

        $callBack = $this->request->param('callback', '');
        $this->assign('callback', $callBack);
        $this->assign('user', $user);
        if ($this->request->isPost()) {
            $bankName = $this->request->param('bankName', '');
            $userName = $this->request->param('userName', '');
            $cardNum = $this->request->param('bankNum', '');
            if ($bankName == '') {
                $this->error('请填写银行名称');
            }
            if ($userName == '') {
                $this->error('请填写真实姓名');
            }
            if ($cardNum == '') {
                $this->error('请填写银行卡号');
            }
            $data = [];
            $data['bank_name'] = $bankName;
            $data['user_name'] = $userName;
            $data['card_num'] = $cardNum;
            $data['updatetime'] = time();
            $row = Db::name("user")->data($data)->where(['id' => $userId])->update();
            if ($row) {
                $callBack = ($callBack == 1 ? url('index/user/withdrawView', '', false, true) : '');
                $this->success('保存成功', $callBack);
            }
        }
        return $this->view->fetch("setting_paytype");
    }

    function setqrcode()
    {

        if ($this->request->isPost()) {
            $path = $this->request->param('path');
            if (empty($path)) {
                $this->error('请上传下单二维码');
            }
            $row = Db::name("user")->where(["id" => $this->auth->id])->data(['qr_code' => $path, 'updatetime' => time()])->update();
            if ($row) {
                $this->success('保存成功！');
            }
            $this->error('非法操作');
        }
        $bak = $this->request->param('bak', '');
        if ($bak == 1) {
            $bak = url('index/task/upgrade');
        }
        $this->assign('bak', $bak);
        $user = Db::name("user")->where(["id" => $this->auth->id])->find();
        $this->assign('user', $user);
        return $this->view->fetch("setqrcode");
    }

    /*
     * 修改个人信息
     */
    public function userinfo()
    {

        if ($this->request->isPost()) {
            $gender = $this->request->param('gender');
            $nickname = $this->request->param('nickname');
            $avatar = $this->request->param('path');
            if (!in_array($gender, [0, 1, 2])) {
                $this->error('非法输入！');
            }
            if ($nickname == '') {
                $this->error('请输入昵称');
            }
            if ($avatar == '') {
                $this->error('请设置头像');
            }

            $row = Db::name('user')->where(["id" => $this->auth->id])->data(['avatar' => $avatar, 'nickname' => $nickname, 'gender' => $gender, 'updatetime' => time()])->update();
            if ($row) {
                $this->success('保存成功！');
            }
            $this->error('错误！请重试！');
        }


        $user = Db::name('user')->where(["id" => $this->auth->id])->find();
        if (!$user["avatar"]) {
            $user["avatar"] = $user["avatar"] ? cdnurl($user["avatar"]) : letter_avatar($user["nickname"]);
        }
        $this->assign("user", $user);
        return $this->view->fetch();
    }

    /*
     * 我的收获地址
     */
    public function myaddress()
    {
        $userId = $this->auth->id;

        $addr = Db::name('shopro_user_address')->where(['user_id' => $userId])->find();
        if ($this->request->isPost()) {
            $consignee = $this->request->param('consignee');
            $phone = $this->request->param('phone');
            $address = $this->request->param('address');
            $province_city_area = $this->request->param('province_city_area');
            if ($consignee == '') {
                $this->error('请输入收货人');
            }
            if ($phone == '') {
                $this->error('请输入手机号');
            }
            if ($province_city_area == '') {
                $this->error('请输入省市区');
            }
            if ($address == '') {
                $this->error('请输入详细地址');
            }
            $data = [];
            $data['consignee'] = $consignee;
            $data['phone'] = $phone;
            $data['address'] = $address;
            $data['province_city_area'] = $province_city_area;
            $data['updatetime'] = time();
            if (empty($addr)) {
                $data['user_id'] = $userId;
                $data['createtime'] = time();
                $data['is_default'] = 1;
                $row = Db::name('shopro_user_address')->data($data)->insert();
            } else {
                $row = Db::name('shopro_user_address')->data($data)->where(["id" => $addr['id']])->update();
            }
            if ($row) {
                $this->success('保存成功！');
            }
            $this->error('错误！请重试！');
        }

        $this->assign('hasAddr', empty($addr) ? 0 : 1);
        $this->assign('addr', $addr);
        return $this->view->fetch();
    }
}
